package com.yi.wood.web.interceptor;

import com.yi.wood.base.Result;
import com.yi.wood.base.ResultCodeEnum;
import com.yi.wood.service.exception.BusinessException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * @author moyi
 * @since 1.0
 */
@RestControllerAdvice
public class ExceptionAdvice {

    /**
     * 统一处理运行时的异常
     * @param e 异常
     * @return 封装统一返回结果
     */
    @ExceptionHandler(value = Exception.class)
    public Object businessExceptionHandler(Exception e){
        if (e instanceof BusinessException){
            BusinessException exception = (BusinessException)e;
            return exception.getResult();
        } else if(e instanceof ConstraintViolationException){
            // 参数校验出错
            return new Result(ResultCodeEnum.ERROR_PARAMETER,null);
        } else if(e instanceof IllegalArgumentException){
            return new Result(ResultCodeEnum.SYSTEM_EXCEPTION, e.getMessage());
        }else {
            e.printStackTrace();
            return new Result(ResultCodeEnum.SYSTEM_EXCEPTION,null);
        }
    }

    /**
     * 统一处理请求异常
     * @param request 请求的request对象
     * @param e 异常
     * @return 封装统一返回结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object requestParamException(HttpServletRequest request, Exception e){
        if (e instanceof MethodArgumentNotValidException){
            return new Result(ResultCodeEnum.ERROR_PARAMETER, e.getMessage());
        }
        return new Result(ResultCodeEnum.ERROR_PARAMETER, "");
    }
}
